<template>
    <div>
        <div class="row">
            <div class="col-md-4 col-sm-4">
                <div class="card-body">

                    <h4>我的家人</h4>
                    <ul>
                        <li v-for="participant in participants" v-text="participant.name"></li>
                    </ul>
                </div>
            </div>
            <div class="col-md-8 col-sm-8">
                <div class="card-body">
                    <ul class="list-group">
                        <li class="list-group-item" v-for="task in project.tasks" v-text="task.body"></li>
                    </ul>
                    <ul class="list-group">
                        <li class="list-group-item">
                            <input type="text" v-model="newTask" class="form-control" @blur="save"
                                   @keydown="tapParticipants">
                            <span v-if="activePeer" v-text="activePeer.name+' 正在输入...'"></span>
                        </li>
                    </ul>
                </div>
            </div>

        </div>
    </div>
</template>

<script>
  export default {
    data() {
      return {
        project: this.dataProject,
        newTask: '',
        activePeer: false,
        typingTimer: false,
        participants: []
      }
    },
    props: ['data-project'],
    created() {
      this.channel
        .here(users => {
          console.log('here')
          console.log(users)
          this.participants = users;
        })
        .joining(user => {
          console.log('joining')
          console.log(user)
          this.participants.push(user);
        })
        .leaving(user => {
          console.log('leaving')
          console.log(user)
          this.participants.splice(this.participants.indexOf(user), 1);
        })
        .listen('TaskCreated', ({task}) => {
          this.addTask(task)
        })
        .listenForWhisper('typing', this.whisperHandler)
    },
    methods: {
      whisperHandler(e) {
        this.activePeer = e;
        if (this.typingTimer) clearTimeout(this.typingTimer)
        this.typingTimer = setTimeout(() => {
          this.activePeer = false;
        }, 3000);
      },
      tapParticipants() {
        this.channel
          .whisper('typing', {name: window.app.user.name})
      },
      save() {
        if (this.newTask !== '') {

          axios.post(`/api/projects/${this.project.id}/tasks`, {body: this.newTask})
            .then(response => response.data)
            .then(this.addTask);
        }
        this.newTask = '';


      },
      addTask(task) {
        this.project.tasks.push(task);
      }
    },
    computed: {
      channel() {
        return window.Echo.join('tasks.' + this.project.id);
      }
    }
  }
</script>
